//
//  ModelData.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/2.
//

import Foundation
import Combine

class ModelData: ObservableObject {
    static let shared = ModelData() // 单例实例
    
    @Published var quotes: [String] = load("quotes.json")
    @Published var noises: [Noise] = load("noises.json") {
        didSet {
            if !isUpdatingSelection {
                updateSelectedNoise()
            }
        }
    }
    var radomQuote: String {
        if quotes.count > 0 {
            return quotes[Int.random(in: 0..<quotes.count)]
        }
        return "今天的坚持，是明天的回报"
    }
    
    @Published var currentSelectedNoise: Noise?
    
    private var isUpdatingSelection = false // 用于避免递归调用
    
    private init() {
        updateSelectedNoise()
    }
    
    func selectedNoise(noise: Noise) {
        currentSelectedNoise?.isSelected = false
        noise.isSelected = true
        currentSelectedNoise = noise
        UserDefaults.standard.setValue(noise.id, forKey: "SELECTED_NOISE_ID")
    }
    
    private func updateSelectedNoise() {
        guard !noises.isEmpty else { return }
        
        let selectedNoiseID = UserDefaults.standard.integer(forKey: "SELECTED_NOISE_ID")
        
        if selectedNoiseID == 0 {
            if let firstNoise = noises.first {
                UserDefaults.standard.setValue(firstNoise.id, forKey: "SELECTED_NOISE_ID")
                updateNoiseSelection(id: firstNoise.id)
            }
        } else {
            updateNoiseSelection(id: selectedNoiseID)
        }
    }
    
    private func updateNoiseSelection(id: Int) {
        isUpdatingSelection = true // 设置标志位以避免递归
        for index in noises.indices {
            noises[index].isSelected = noises[index].id == id
            if noises[index].id == id {
                currentSelectedNoise = noises[index]
            }
        }
        isUpdatingSelection = false // 重置标志位
    }
}

func load<T: Decodable>(_ filename: String) -> T {
    let data: Data
    
    guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else {
        fatalError("Couldn't find \(filename) in main bundle.")
    }
    
    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
    
    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}
